<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class It_menu extends MY_Controller {
	
	function __construct()
	{
		parent::__construct(); 
		
		$this->load->model('it_menu_model', 'Menu');
		$this->secure_session();
	}
	
	function index(){
		$data['title'] = "Setup Menu";
		viewByTemplate('it_menu/index', $data, 'grid');
	}
	
	function treegrid_data(){
		$this->secure_session();
		echo json_encode($this->Menu->GetTreeData());
	}
	
	function treegrid_subdata($parent_id=''){
		$this->secure_session();
		echo json_encode($this->Menu->GetTreeSubData($parent_id));
	}
	
	function combotree_data(){
		$this->secure_session();
		echo json_encode($this->Menu->GetComboTreeData());
	}
	
	function getimportdata()
	{
		$filepath		= APPPATH . '/file/upload/'.md5(USERID).'.json';
		$file_content	= read_file($filepath);
		echo (trim($file_content) == '' ? '[]' : $file_content);
	}
	
	function create()
	{
		$data['title'] = "Setup Menu - Create";
		$data['data'] = NULL;
		$data['data']['parent_menu_id']	= get('menu_id');
		$data['data']['url']			= '#';
		
		$data['parent_data']	= json_encode($this->Menu->GetComboTreeData());
		
		$data['mode'] = "create";
		viewByTemplate('it_menu/form', $data, 'form');
	}

	function edit()
	{
		$data['title'] = "Setup Menu - Edit";
		$data['data'] = $this->Menu->GetSingleView(get('menu_id'));
		
		$data['parent_data']	= json_encode($this->Menu->GetComboTreeData());
		
		$data['mode'] = "edit";
		viewByTemplate('it_menu/form', $data, 'form');
	}

	private function validation()
	{
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty = $this->MessageTemplate("ER001");
		$tpl_duplicate = $this->MessageTemplate("ER002");


		// Validation
		if (post("menu_label") == '') {
			$error->Add("menu_label", "Label Menu", $tpl_empty);
		}
		
		if (post("url") == '') {
			$error->Add("url", "URL", $tpl_empty);
		}

		return $error;
	}
	
	function ajax_post()
	{
		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";

		$error = $this->validation();
		try
		{
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else
			{
				// Fill Post Data
				$data	= post_by_key(array('menu_id', 'parent_menu_id', 'menu_label', 'url', 'order_num', 'status'));
				
				if (post("mode") == "create")
				{
					$menu_id		= $this->get_data("SELECT (NVL((SELECT MAX(SUBSTR(MENU_ID,".(strlen(APP)+1).",".(10-strlen(APP)).")+0) FROM IT_MENU WHERE APP_ID = '".APP."'),0)+1) MENU_ID FROM DUAL");
					$menu_id		= APP . str_pad($menu_id, 10-strlen(APP), '0', STR_PAD_LEFT);
					$ls_genid		= $menu_id;
					$data['menu_id']		= $menu_id;
					$data['app_id']			= APP;
					$data['create_date']	= NOW;
					$data['create_user']	= USERID;

					$this->Menu->Add($data);

					$ls_response = "Data Tersimpan";
					//App.audit_trail("CS001", "create/" + (data.role_id ?? ""));

				}
				else if (post("mode") == "edit")
				{
					$data['modify_date']	= NOW;
					$data['modify_user']	= USERID;
					
					$this->Menu->Update($data, 
										array('menu_id'	=> $data['menu_id']));

					$ls_response = "Data Tersimpan";
					//App.audit_trail("CS002", "edit/" + (data.role_id ?? ""));

				}
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
													'fields'	=> $error->GetDictionary(),
													'msg'		=> $ls_response,
													'genid'		=> $ls_genid,
													'form_sender'=> post("form_sender"))
								));
	}

	function ajax_delete()
	{
		$ls_result	= "";
		$menu_id	= get('menu_id');
		
		if ($menu_id != "")
		{
			// Delete Single
			$ls_result = $this->Menu->DeleteSingle($menu_id);

		}
		else
		{
			
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++)
			{
				$row	= $this->data['deleted'][$i];
				$ls_result .= $this->Menu->DeleteSingle($row['menu_id']);
			}
		}
		
		echo $ls_result;
	}
	
	function export(){
		$export_file	= APPPATH . '/file/cache/' . _SESSID.'.json';
		
		$arr_menu	= $this->Menu->GetTreeData();
		
		write_file($export_file, json_encode($arr_menu), 'a+');
	}
	
	function form_import(){
		$data['title'] = "Import Menu From JSON File";
		
		$filepath	= APPPATH . '/file/upload/'.md5(USERID).'.json';
		@unlink($config['upload_path'].$filepath);
				
		$this->load->view('it_menu/form_import', $data);
	}
	
	function process_upload_file(){
		$is_error		= 0;
		$arr_allowed	= array('json');
		$config['upload_path']		= APPPATH . '/file/upload/';
		$config['allowed_types']	= $arr_allowed;
		$this->load->library('upload', $config);
		
		$error = new ErrorList();
		
		// Get Error Template
		$tpl_empty		= $this->MessageTemplate("ER001");
		$tpl_duplicate	= $this->MessageTemplate("ER002");
		$tpl_typefile	= $this->MessageTemplate("ER011");
		$tpl_filesize	= $this->MessageTemplate("ER013");
		$tpl_upload_success = $this->MessageTemplate("CS004");
		
		// Get Server Maximum Upload File Size 
		// (publisher : http://www.kavoir.com/2010/02/php-get-the-file-uploading-limit-max-file-size-allowed-to-upload.html)
		$max_upload		= (int)(@ini_get('upload_max_filesize'));
		$max_post		= (int)(@ini_get('post_max_size'));
		$memory_limit	= (int)(@ini_get('memory_limit'));
		$max_upload_mb	= @min($max_upload, $max_post, $memory_limit);
		$content_length	= (array_key_exists('CONTENT_LENGTH',$_SERVER) ? $_SERVER['CONTENT_LENGTH'] : 0);
		
		// Validation
		$has_file	= false; $arr_uploaded	= array();
		if($content_length/1048576 > $max_upload_mb){
			$ls_response	= $tpl_filesize['message_id'];
			$ls_response	= str_replace('{0}', stringFileSize($content_length), $ls_response);
			$ls_response	= str_replace('{1}', $max_upload_mb.'MB', $ls_response);
			
			$is_error = 1;
		}else{
			$filename	= $_FILES['my_file']['name'];
			$ext		= strtolower(end(explode('.', $filename)));
			
			if(trim($filename) != ''){
				$new_filename	= md5(USERID);
				
				@unlink($config['upload_path'].$new_filename.'.'.$ext);
				
				if(!in_array($ext, $arr_allowed)){
					$ls_response	= $tpl_typefile['message_id'];
					$ls_response	= str_replace('{0}', '["'.$ext.'"]', $ls_response);
					$ls_response	= str_replace('{1}', json_encode($arr_allowed), $ls_response);
					
					$is_error = 1;
				}else if ( !$this->upload->do_upload('my_file'.$i, $new_filename) )
				{
					$ls_response = $this->upload->display_errors('', '');
					
					if(trim($ls_response) == ''){ $is_error = 1; }
				}
			}else{
				$ls_response	= $tpl_empty['message_id'];
				$ls_response	= str_replace('{0}', 'File', $ls_response);

				$is_error = 1;
			}
		}
		
		if($is_error == 1){
			echo '<script type="text/javascript">parent.setLoading(false); parent.$.messager.alert("Error","'.addslashes($ls_response).'","error");</script>';
		}else{
			echo '<script type="text/javascript">parent.f_import_file_to_db("'.$new_filename.'.'.$ext.'");</script>';
		}
	}
	
	function import_file_to_db(){
		$filename 		= post('filename');
		$path 			= APPPATH . '/file/upload/' . $filename;
		
		@set_time_limit(0);				// ignore php timeout
		//@ignore_user_abort(true);		// keep on going even if user pulls the plug*
		
		$err_message	= '';
		try {
			$arr_data	= json_decode(read_file($path));
			if(count($arr_data) == 0){
				$err_message = 'No Data';
			}
		} catch(Exception $e) {
			$err_message = $e->getMessage();
		}
		
		if($err_message == ''){
			echo "setLoading(false); grid_import_reload(); $('#label_file_import, #my_file, #btn_upload').hide(); $('#btn_import, #btn_new_import').fadeIn();"; die;
		}else{
			echo 'setLoading(false); $("#datagrid_import").treegrid("loadData", []); $.messager.alert("Notification","'.addslashes($err_message).'","ok");';
			echo "f_new_import();";
		}
	}
	
	function import_transfer(){
		// ------------------------------
		// Process your data here
		// ------------------------------
		try {
			$filepath	= APPPATH . '/file/upload/'.md5(USERID).'.json';
			$arr_data	= json_decode(read_file($filepath));
			
			$this->db->query("DELETE FROM IT_MENU_ACCESS WHERE MENU_ID IN (SELECT MENU_ID FROM IT_MENU WHERE APP_ID = '".APP."')");
			$this->db->query("DELETE FROM IT_MENU WHERE APP_ID = '".APP."'");
			
			$this->__AddMenuImport($arr_data);
			$this->db->query("INSERT INTO IT_MENU_ACCESS (CR, UP, DL,PR, DW, UPL,ROLE_ID, MENU_ID) SELECT '1','1','1','1','1','1','".ROLE."', MENU_ID FROM IT_MENU WHERE APP_ID = '".APP."'");
			
			@unlink($config['upload_path'].$filepath);
		
			echo 'setLoading(false); $.messager.alert("Success","Proses Import Selesai","ok", function(){  setLoading(); redirect(gs_path+"/app/system/"); }); ';
		} catch(Exception $e) {
			echo $e->getMessage();
			echo 'setLoading(false); grid_import_reload(); grid_reload(); f_new_import(); $.messager.alert("Error","'.addslashes($e->getMessage()).'","error"); ';
		}
	}
	
	// Import By Level
	private function __AddMenuImport($arr_data, $parent_menu_id = '0'){
		$order_num	= 10;
		for($i=0,$max_i=count($arr_data); $i<$max_i; $i++){
			$rowStdClass	= $arr_data[$i];
			$row			= get_object_vars($rowStdClass);
			$row['parent_menu_id']	= $parent_menu_id;
			$row['order_num']		= $order_num;
			$order_num += 10;
			
			$menu_id	= $this->__AddMenuSingleImport($row);
			if(	$menu_id != '' && 
				array_key_exists('numchild',$row) && 
				$row['numchild'] > 0 && 
				array_key_exists('children',$row) && is_array($row['children']) && 
				count($row['children']) > 0){
					$this->__AddMenuImport($row['children'], $menu_id);
			}
		}
	}
	
	// Import By Row
	private function __AddMenuSingleImport($row){
		$menu_id = '';
		if(is_array($row) && array_key_exists('menu_label', $row) && trim($row['menu_label']) != ''){
			$menu_id		= $this->get_data("SELECT (NVL((SELECT MAX(SUBSTR(MENU_ID,".(strlen(APP)+1).",".(10-strlen(APP)).")+0) FROM IT_MENU WHERE APP_ID = '".APP."'),0)+1) MENU_ID FROM DUAL");
			$menu_id		= APP . str_pad($menu_id, (10 - strlen(APP)), '0', STR_PAD_LEFT);
			
			$data	= array('menu_id'		=> $menu_id,
							'app_id'		=> APP,
							'parent_menu_id'=> $row['parent_menu_id'],
							'menu_label'	=> $row['menu_label'],
							'icon'			=> $row['icon'],
							'url'			=> $row['url'],
							'order_num'		=> $row['order_num'],
							'status'		=> $row['status'],
							'create_date'	=> NOW,
							'create_user'	=> USERID);
			
			$this->Menu->Add($data);
		}
		return $menu_id;
	}
}
?>